<template>
  <div class="iat">
    <div class="iat-title">
      {{ $t("title") }}
      <span @click="goTo" class="iat-title-file">
        <img :src="fileIcon" alt="" />
        {{ $t("文件中心") }}
      </span>
    </div>
    <div class="iat-desc">
      {{ $t("tips") }}
    </div>
    <div class="iat-content">
      <!-- 原文 -->
      <div class="iat-content-item">
        <div class="iat-content-item-header">
          <div>
            <div
              @click="clickAi(1, false)"
              :class="`iat-content-item-header-btn ${IsOriginAi ? '' : 'iat-content-item-header-btn-active'}`"
            >
              {{ $t("theOrigin") }}
            </div>
            <div
              style="margin-left: 20px"
              @click="clickAi(1, true)"
              :class="`iat-content-item-header-btn ${IsOriginAi ? 'iat-content-item-header-btn-active' : ''}`"
            >
              {{ $t("theTrans") }}
            </div>
            <div style="margin: 0 20px" class="iat-content-item-header-select">
              <img :src="originImg[locale]" alt="" />
              <a-select :disabled="recordStatus" v-model:value="target">
                <a-select-option
                  v-for="item in originList"
                  :key="item.code"
                  :value="item.code"
                  >{{ locale === "cn" ? item.cn : item.name }}</a-select-option
                >
              </a-select>
            </div>
          </div>
        </div>
        <div
          ref="originRef"
          :class="`iat-content-item-text ${target === 'ar' ? 'arabic-text' : ''} ${IsOriginAi && loading ? 'loading' : ''}`"
          :style="{
            textAlign: target === 'ar' && !loading ? 'right' : 'left',
          }"
        >
          <a-spin v-if="loading && IsOriginAi" size="large" />
          {{ IsOriginAi ? AIoriginText : originText }}
        </div>
        <div v-show="!recordStatus" class="iat-content-item-recordIng">
          <img @click="start" :src="voice" />
        </div>
        <div v-show="recordStatus" class="iat-content-item-record">
          <div class="iat-content-item-record-time">
          </div>
          <canvas id="waveform"></canvas>
          <img @click="close" :src="stopIcon" />
        </div>
      </div>
      <div v-if="transList.length" class="iat-content-hr"></div>
      <!-- 译文 -->
      <div v-if="transList.length" class="iat-content-item">
        <div class="iat-content-item-header">
          <div class="iat-content-item-header-select">
            <img :src="transImg[locale]" alt="" />
            <a-select :disabled="IsTransAi || recordStatus" v-model:value="src" allowClear>
              <a-select-option
                v-for="item in transList"
                :key="item.from"
                :value="item.from"
                >{{ locale === "cn" ? item.cn : item.name }}</a-select-option
              >
            </a-select>
          </div>
          <div>
            <div
              @click="clickAi(2, false)"
              :class="`iat-content-item-header-btn ${IsTransAi ? '' : 'iat-content-item-header-btn-active'}`"
            >
              {{ $t("theOrigin") }}
            </div>
            <div
              @click="clickAi(2, true)"
              :class="`iat-content-item-header-btn ${IsTransAi ? 'iat-content-item-header-btn-active' : ''}`"
            >
              {{ $t("theTrans") }}
            </div>
          </div>
        </div>
        <div
          ref="transRef"
          :class="`iat-content-item-text ${src === 'ar' ? 'arabic-text' : ''} ${IsTransAi && loading1 ? 'loading' : ''}`"
          :style="{
            textAlign: src === 'ar' && !loading1 ? 'right' : 'left',
          }"
        >
          <a-spin v-if="loading1 && IsTransAi" size="large" />
          {{ IsTransAi ? AItransText : transText }}
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref } from "vue";
import fileIcon from "@/assets/imgs/files.png";
import { iatLanguage } from "./language.js";
import { watch } from "vue";
import dialectIcon from "@/assets/imgs/dialect.png";
import { EngineType } from "./config.js";
import { message } from "ant-design-vue";
import { copywritingSummary } from "@/service/web";
import i18n from "@/config/lang.ts";
import transIcon from "@/assets/imgs/trans.png";
import transEnIcon from "@/assets/imgs/trans_en.png";
import originIcon from "@/assets/imgs/origin.png";
import originEnIcon from "@/assets/imgs/origin_en.png";
import IatRecord from "@/utils/speech/iat.js";
import voice from "@/assets/imgs/voice1.png";
import useDict from "@/hooks/useDict";
import stopIcon from "@/assets/imgs/stop.png";
const loading = ref(false);
const loading1 = ref(false);
const router = useRouter();
const IatSpeech = new IatRecord(callback, close);
const locale = i18n.global.locale.value;
const originImg = {
  en: originEnIcon,
  cn: originIcon,
};
const list = Object.values(iatLanguage); //源语种所有语言
const transImg = {
  cn: transIcon,
  en: transEnIcon,
};
const originRef = ref(null);
const transRef = ref(null);
// 原文
const originText = ref("");
const AIoriginText = ref("");
// 译文
const transText = ref("");
const AItransText = ref("");
// 语种
// 是否开启AI
const IsOriginAi = ref(false);
// 是否译文开启AI
const IsTransAi = ref(false);
// 是否开启录音
const recordStatus = ref(false);
// 源语种
const originList = ref([]);
// 译文语种
const transList = ref([]);
// 原文
const target = ref("");
// 译文
const src = ref("");
// 倒计时
const time = ref(60);
// AI总结原文次数限制
let AIOriginLock = true;
// AI总结译文次数限制
let AISrcLock = true;

let timer = null;

watch(
  () => src.value,
  async () => {
    transText.value = "";
    await IatSpeech.getTranslationUrl(
      originText.value,
      target.value,
      src.value
    );
    AItransText.value = "";
    AISrcLock = true;
  }
);

watch(
  () => target.value,
  () => {
    src.value = "";
    resetStatus();
    transList.value = [];
    src.value = "";
    originList.value.some((a) => {
      if (a.code === target.value) {
        transList.value = a.children || [];
        transList.value.length && (src.value = transList.value[0]?.from);
        return true;
      }
    });
    // }
  }
);

function resetStatus() {
  originText.value = "";
  transText.value = "";
  AIoriginText.value = "";
  AItransText.value = "";
  AIOriginLock = true;
  AISrcLock = true;
  IsOriginAi.value = false;
  IsTransAi.value = false;
  loading.value = false;
  loading1.value = false;
}

// type 1 原文  2 译文
init();
async function init() {
  originList.value = list;
  if (list.length) {
    target.value = list.length && list[0].code;   //初始原文下拉语言
    transList.value = list[0].children;           //初始译文下拉语言
  }
}

function clickAi(type, status) {
  if (recordStatus.value) {
    message.warning(t("askRecord"));
    return;
  }
  if (status) {
    if (type == 1) {
      if (!originText.value) {
        message.warning(t("originTextNull"));
        return;
      }
    } else {
      if (!transText.value) {
        message.warning(t("srcTextNull"));
        return;
      }
    }
    getAIText(type);
  }
  if (type === 1) {
    IsOriginAi.value = status;
  } else {
    IsTransAi.value = status;
  }
}

function callback(data) {
  const { text, translation = "" } = data;
  text && (originText.value = text);
  translation && (transText.value = translation);
  if (originRef.value) {
    const ele = originRef.value;
    ele.scrollTop = ele.scrollHeight - ele.clientHeight;
  }
  if (transRef.value) {
    const ele = transRef.value;
    ele.scrollTop = ele.scrollHeight - ele.clientHeight;
  }
}

function close(status = true) {
  clearInterval(timer);
  recordStatus.value = false;
  time.value = 60;
  status && IatSpeech.stopRecord();
}

// 录音开始
function start() {
  let obj = {
    origin: "",
    ent: "",
  };
  resetStatus();
  console.log(originList,'------originList  源语种------');
  
  originList.value.some((a) => {
    if (a.code === target.value) {      //源语种的配置
      obj = {
        ent: a.ent,
        origin: a.language,
        code: a.code,
        parames: a.parames,
        type: a.type,
        isAddUrl : a.isAddUrl
      };
      return true;
    }
  });
  IatSpeech.startRecording(
    {
      language: target.value === "mq_cbm" ? "en" : target.value,   //原文语言为全语种，设置入参为en
      src: src.value, //译文语言                                         
      ...obj,
    },
    () => {
      clearInterval(timer);
      recordStatus.value = true;
      if (obj.type !== 2) {
        timer = setInterval(() => {
          if (!time.value) {
            close();
            return;
          }
          time.value--;
        }, 1000);
      }
    },
    // 错误函数
    () => {
      message.error(t("networkError"));
      close();
    }
  );
}

// ai调用 type
async function getAIText(type) {
  // 延迟发送AI总结
  if (type === 1) {
    if (!AIOriginLock) {
      return;
    }
    loading.value = true;
    AIOriginLock = false;
    AIoriginText.value = "";
  } else if (type === 2) {
    if (!AISrcLock) {
      return;
    }
    loading1.value = true;
    AISrcLock = false;
    AItransText.value = "";
  }
  try {
    let language = 'en'
    originList.value.some((a) => {
      if (a.code === target.value) {
        language = a.value
        return true;
      }
    });
    const { data } = await copywritingSummary({
      copywriting: type === 1 ? originText.value : transText.value,
      language: type === 1 ? language : src.value,
    });
    if (type === 1) {
      loading.value = false;
      AIoriginText.value = data;
    } else {
      loading1.value = false;
      AItransText.value = data;
    }
  } catch (err) {
    if (type === 1) {
      loading.value = false;
      AIOriginLock = true;
    } else {
      loading1.value = false;
      AISrcLock = true;
    }
  }
}

function goTo() {
  if (recordStatus.value) {
    message.warning(t("askRecord"));
    return;
  }
  router.push("/file-center?type=1");
}
</script>
<style>
.ant-select-selector {
  border-color: transparent !important;
  box-shadow: none !important;
}

.ant-select-selector:focus {
  border-color: transparent !important;
  box-shadow: none !important;
}
</style>
<style lang="scss" scoped>
.loading {
  display: flex;
  align-items: center;
  justify-content: center;
}

#waveform {
  width: 200px;
  height: 90px;
}

/* 单个条形 */
.wave-bar {
  width: 4px;
  background: linear-gradient(180deg, rgb(79, 151, 255) 24%, rgb(39, 94, 255));
  border-radius: 4px; /* 圆角 */
  animation: wave 1.2s ease-in-out infinite; /* 动画 */
}

.arabic-text {
  font-family: "Amiri", "Arial", sans-serif;
  direction: rtl;
  unicode-bidi: plaintext; /* 👈 关键属性 */
}

/* 波形动画 */
@keyframes wave {
  0%,
  100% {
    height: 20%; /* 最小高度 */
  }
  50% {
    height: 100%; /* 最大高度 */
  }
}
.iat {
  width: 85vw;
  margin: 0 auto;
  background-color: #353744;
  &-title {
    height: 4.4vh;
    font-size: 34px;
    font-family:
      PingFang SC,
      PingFang SC-Medium;
    font-weight: 500;
    text-align: center;
    color: #ffffff;
    line-height: 48px;
    text-align: center;
    &-file {
      position: absolute;
      right: 40px;
      top: 100px;
      display: flex;
      align-items: center;
      font-size: 18px;
      font-family:
        PingFang SC,
        PingFang SC-Regular;
      font-weight: 400;
      text-align: center;
      color: #b7b8bf;
      cursor: pointer;
      img {
        height: 28px;
        width: 28px;
        margin-right: 4px;
      }
    }
  }
  &-desc {
    margin: 17px auto 0;
    width: 1120px;
    height: 6vh;
    font-size: 18px;
    font-family:
      PingFang SC,
      PingFang SC-Regular;
    font-weight: 400;
    text-align: center;
    color: rgba(255, 255, 255, 0.4);
    line-height: 32px;
    text-align: center;
  }
  &-content {
    margin-top: 21px;
    width: 100%;
    height: 64vh;
    box-sizing: border-box;
    background: url("@/assets/imgs/iatBG.png");
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
    // border-image: linear-gradient(180deg, #2b2f48, rgba(43, 47, 72, 0)) 1 1;
    border-radius: 24px;
    // backdrop-filter: blur(30px);
    display: flex;
    border: 1px solid rgba(26, 27, 35, 0.2);
    &-item {
      width: calc(100% - 1px / 2);
      padding: 24px;
      &-recordIng {
        height: 10vh;
        display: flex;
        align-items: center;
        justify-content: center;
        img {
          width: 72px;
          height: 72px;
          cursor: pointer;
        }
      }
      &-record {
        height: 10vh;
        background: linear-gradient(135deg, #2a2e3c, #272936);
        border-radius: 14px;
        padding: 24px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: space-between;
        img {
          width: 32px;
          height: 32px;
          cursor: pointer;
        }
      }
      &-header {
        display: flex;
        justify-content: space-between;
        height: 44px;
        &-select {
          width: 200px;
          height: 44px;
          border: 2px solid rgba(62, 69, 78, 0.55);
          border-radius: 14px;
          display: flex;
          align-items: center;
          padding: 0 10px;
          &-other {
            height: 44px;
            border: 2px solid rgba(62, 69, 78, 0.55);
            border-radius: 14px;
            display: flex;
            align-items: center;
            ::v-deep(.ant-select-selector) {
              background-color: transparent !important;
              border-color: transparent;
            }
          }
          ::v-deep(.ant-select-selector) {
            min-width: 160px;
            background-color: transparent !important;
            border-color: transparent;
          }
          img {
            width: 24px;
            height: 24px;
          }
        }
        > div {
          display: flex;
          justify-content: space-around;
        }
        &-btn {
          height: 44px;
          background: rgba(40, 141, 255, 0.12);
          border-radius: 14px;
          padding: 10px 16px;
          display: flex;
          justify-content: center;
          align-items: center;
          cursor: pointer;
          &-active {
            background: #288dff;
          }
          &:last-of-type {
            margin-left: 20px;
          }
        }
      }
      &-text {
        line-height: 22px;
        height: 40vh;
        overflow-y: auto;
        margin-top: 30px;
        font-size: 18px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        text-align: left;
        color: rgb(255, 255, 255, 0.8);
      }
    }
    &-hr {
      width: 1px;
      background-color: #313653;
    }
  }
}
</style>
